package com.imooc.pan.server.common.mq.consumer.search;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.imooc.pan.core.utils.IdUtil;
//import com.imooc.pan.server.common.mq.config.RabbitMQConfig;
import com.imooc.pan.server.common.mq.event.search.UserSearchEvent;
import com.imooc.pan.server.modules.user.entity.RPanUserSearchHistory;
import com.imooc.pan.server.modules.user.service.IUserSearchHistoryService;
import lombok.extern.slf4j.Slf4j;
//import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * 用户搜索事件监听器
 */
@Component
@Slf4j
public class UserSearchEventConsumer {

    @Autowired
    private IUserSearchHistoryService iUserSearchHistoryService;

    /**
     * 监听用户搜索事件，将其保存到用户的搜索历史记录当中
     *
     * @param message
     */
    //@StreamListener(PanChannels.USER_SEARCH_INPUT)
//    @RabbitListener(queues = RabbitMQConfig.USER_SEARCH_QUEUE)
    public void saveSearchHistory(String message) {
        if (Objects.isNull(message)) {
            return;
        }
        log.info("save search history message {} has been received", message);

        //printLog(message);
        UserSearchEvent event = JSON.parseObject(message, UserSearchEvent.class);
        //UserSearchEvent event = message.getPayload();
        RPanUserSearchHistory record = new RPanUserSearchHistory();

        record.setId(IdUtil.get());
        record.setUserId(event.getUserId());
        record.setSearchContent(event.getKeyword());
        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());

        try {
            iUserSearchHistoryService.save(record);
        } catch (DuplicateKeyException e) {
            UpdateWrapper updateWrapper = Wrappers.update();
            updateWrapper.eq("user_id", event.getUserId());
            updateWrapper.eq("search_content", event.getKeyword());
            updateWrapper.set("update_time", new Date());
            iUserSearchHistoryService.update(updateWrapper);
        }
    }
}
